package cn.yzfy.framework.starter.common.utils;

import cn.yzfy.framework.starter.common.threadpool.proxy.RejectedProxyInvocationHandler;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Proxy;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author: 一朝风月
 * @Date: 2025/8/7 10:45
 * @Code 珍琅Code 研发
 * @Version: 1.0
 * @Description
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)

public class RejectedProxyUtil {
    /**
     * 创建拒绝策略代理类
     *
     * @param rejectedExecutionHandler 真正的线程池拒绝策略执行器
     * @param rejectedNum              拒绝策略执行统计器
     * @return 代理拒绝策略
     */
    public static RejectedExecutionHandler createProxy(RejectedExecutionHandler rejectedExecutionHandler, AtomicLong rejectedNum) {
        // jdk动态代理模式: 增强线程池拒绝策略，比如：拒绝任务报警或加入延迟队列重复放入等逻辑
        return (RejectedExecutionHandler) Proxy
                .newProxyInstance(
                        rejectedExecutionHandler.getClass().getClassLoader(),
                        new Class[]{RejectedExecutionHandler.class},
                        new RejectedProxyInvocationHandler(rejectedExecutionHandler, rejectedNum));
    }
    //测试线程池代理
    public static void main(String[] args) {
        //初始化一个线程池
        ThreadPoolExecutor executor= new ThreadPoolExecutor(1,1,1024, TimeUnit.MILLISECONDS,new ArrayBlockingQueue<>(1));
        ThreadPoolExecutor.AbortPolicy abortPolicy=new ThreadPoolExecutor.AbortPolicy();
        AtomicLong
                 rejectedNum=new AtomicLong();
        RejectedExecutionHandler proxyRejectedExecutionHandler = RejectedProxyUtil.createProxy(abortPolicy, rejectedNum);

        executor.setRejectedExecutionHandler(proxyRejectedExecutionHandler);
        for (int i = 0; i < 5; i++) {
            try {
                executor.execute(() -> ThreadUtil.sleep(100000L));
            } catch (Exception ignored) {
                ignored.printStackTrace();
            }
        }
        System.out.println("================ 线程池拒绝策略执行次数: " + rejectedNum.get());
    }
//        ApplicationContext ioc=executor.getClass();


}
